package cn.com.youjile.service;

import cn.com.youjile.entity.MsgInfo;
import cn.com.youjile.observer.MsgObserver;
import cn.com.youjile.observer.MsgSubject;
import cn.com.youjile.server.GeneralServer;
import cn.com.youjile.utils.MsgInfoFactory;
import cn.com.youjile.utils.MsgNumUtil;
import cn.com.youjile.utils.ResultUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelMatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 群发
 */
@Slf4j
@Service
public class Broadcast extends MsgObserver {

    public Broadcast(){
        MsgSubject.getInstance().attach(this);
    }

    @Override
    public void update(ChannelHandlerContext ctx, MsgInfo msg) {
        if(msg.getCode() == MsgNumUtil.s_multicast) {
            log.debug("server [" + MsgNumUtil.s_multicast + "] 广播:ctx = [" + ctx + "], msg = [" + msg + "]");
            GeneralServer.allChannels.writeAndFlush(msg, new ChannelMatcher(){ //向不是自己（当前发送人）的所有人群发消息
                @Override
                public boolean matches(Channel channel) {
                    if(channel == ctx.channel()) {
                        return false;
                    } else {
                        return true;
                    }
                }
            });
            //响应
            byte[] success = ResultUtil.success();
            MsgInfo response = MsgInfoFactory.buildMessageInfo(msg.getCode(), success);
            ctx.writeAndFlush(response);
        }
    }
}
